var ROW			=20 ;	
var COLUMN		=10;
var BLOCK_WIDTH	=TETRIS_WIDTH;
var BLOCK_HEIGHT	=TETRIS_WIDTH;
var SQUARE_IMAGE_NUMS	=2;
var BEGIN_X	=3;
var BEGIN_Y	=0;
var NEXT_X	=394;
var NEXT_Y	=20;
var SCREEN_WIDTH	=132;
var SCREEN_HEIGHT	=176;
var SMOKE_NUMS	=5;
var KEY_RESPONSE_TIME	=30;
var LEFT	=0;
var TOP	=-2*BLOCK_HEIGHT;

var i =0 ;
var downNums = 5;
var gameOver = false ;
var pause = false ;
var g = null;

//========================变量声明==============================

var cpx,cpy;
var base ;
var current;
var next;
var bottom;

var cpx,cpy ;
var bottomY;
var gameLevel ;
var score ;	
var moveLineIndex ;
var smokeNums;
var line3Nums;
var line4Nums;

var smoke;
var gameTimer = null ;



function getBlockOffset(num){
	/** return [left,top] */
	return [num%4*TETRIS_WIDTH,parseInt(num/4)*TETRIS_HEIGHT];
}

function mainLoop(){
	if ( gameOver ){
		alert( 'Game Over!\n得分：'+score);
		start();
		return ;
	}
	i++;
	if( i >= downNums )
	{
		paint();
		i = 0;	
		moveDown();
	}
}


var start = function(){
	
	if (base){
		for(var i=0;i<ROW;i++){
			for(var j=0;j<COLUMN;j++){
				base[i][j].remove();
			}
			
		}
	}else{
		base = new Array();
	}
	
	
	
	for(var i=0;i<ROW;i++){
		base[i] = [];
		for(var j=0;j<COLUMN;j++){
			base[i][j] = new Square();
		}
		
	}
	gameOver = false;
	pause = false;
	score = 0;
	
	for( var i=0 ; i< ROW ; i++)
		for( var j =0; j< COLUMN ; j++){
		// base[ i ][ j ] = null ;			
	}
	
	next && next.remove();
	current && current.remove();
	bottom && bottom.remove();
	
	next = getSquareGroup('next',{x:350,y:100});
	
	newGroup();
	
	$('#score').html('得分：'+score);

	gameTimer || (gameTimer = setInterval(mainLoop,150));
};

var paint = function(){

	//paint base
	for( var i=0 ; i< ROW ; i++)
		for( var j =0; j< COLUMN ; j++)
	{
		if( base[i][j] != null)
		{
			base[i][j].draw( j*BLOCK_WIDTH +LEFT, i*BLOCK_HEIGHT +TOP, g);			
		}
	}

	// paint bottom square
	bottom.type = current.type ;
	bottom.orgType = current.orgType;
	bottom.rotateTo(current.degree)
	bottom.applyPosition({x:cpx*BLOCK_WIDTH, y:bottomY*BLOCK_HEIGHT +TOP});
	bottom.draw();

	// paint current SquareGroup
	current.draw();
}
//cpx*BLOCK_WIDTH +LEFT, bottomY*BLOCK_HEIGHT +TOP, g
var newGroup = function()
{		
	cpx  = BEGIN_X;
	cpy  = BEGIN_Y;
	
	current = current || getSquareGroup('current_group');
	current.copy(next);
	current.dom.css('-webkit-transition-property','none');
	current.applyPosition(next.getPosition());	
	
	setTimeout(function(){
	current.dom.css('-webkit-transition-property','all');
	current.applyPosition({x:BEGIN_X*BLOCK_HEIGHT,y:BEGIN_Y*BLOCK_HEIGHT+TOP});	
	if( checkGameOver())
		return;
	next.randomType();
	next.applyPosition({x:350,y:100});
	next.dom.hide();
	next.dom.fadeIn('fast');
	
	bottom = new SquareGroup( {clsType:8 , type:current.getType()} );
	findBottomPosition();	
	bottom.applyPosition({x:cpx*BLOCK_WIDTH, y:bottomY*BLOCK_HEIGHT +TOP});	
	bottom.dom.css('-webkit-transition-property','none');
	bottom.dom.css('opacity','0');
	setTimeout(function(){
		bottom.dom.css('-webkit-transition-property','all');
		bottom.dom.css('opacity','1');
		
	},10);
	
	},10);	
	return ;

};

var checkGameOver = function()
{
	var bias = current.getBias();
	for( var i =0; i< 4; i++)
	{
		if( cpx+bias[i][0] < 0 || base[ cpy +bias[i][1] ][ cpx+bias[i][0] ].cls != null)
		{
			gameOver = true;
			return true;
		}
	}
	return false;
}

var getSquareGroup = function(id,pos)
{
	var type = parseInt( Math.random()*( SquareGroup.TYPE_NUMS ) );
	var cls = parseInt( Math.random()*( SquareGroup.CLS_NUMS ) );

	return new SquareGroup( {clsType:cls , type:type,id:id,p:pos} );
}



var moveLeft = function()
{
	var bias = current.getBias();
	for( var i =0; i< 4; i++)
	{
		if( cpx+bias[i][0]-1 < 0 || base[ cpy +bias[i][1] ][ cpx+bias[i][0]-1 ].cls != null)
		{
			//System.out.println("Can't MoveLeft.");
			return ;
		}
	}
	bottomFlag = false;
	cpx --;
	findBottomPosition();
	
	current.moveLeft();
}

var moveRight = function()
{
	var bias = current.getBias();
	for( var i =0; i< 4; i++)
	{
		if( cpx+bias[i][0]+1 > COLUMN-1 ||  base[ cpy +bias[i][1] ][ cpx+bias[i][0]+1 ].cls != null)
			return ;
	}
	bottomFlag = false;
	cpx ++;
	findBottomPosition();
	
	current.moveRight();
}
var rotate = function()
{
	var rotateBias = current.getRotateBias();

	for( var i =0; i< 4; i++)
	{
		if( cpx+rotateBias[i][0]>=COLUMN || cpy+rotateBias[i][1]+1>=ROW || base[ cpy+rotateBias[i][1] ][  cpx+rotateBias[i][0] ].cls != null )
		{//System.out.println("IN rotate NOT");
			return ;
		}
	}
	bottomFlag = false;
	current.rotate();//System.out.println("out rotate ");
	//bottom.rotate();
	findBottomPosition();
};

var bottomFlag = false ;
var moveDown = function()
{
	//System.out.println("IN moveDown");
	var bias = current.getBias();
	//var x=0,y=0;
	
	if (bottomFlag === true){
		reachBottom();//System.out.println("OUT moveDown");
		return ;
	}
	
	
	for( var i =0; i< 4; i++)//base[x][y];//x:cpx+bias[i][0],Y:cpy+bias[i][1]+1
	{
		if( cpx+bias[i][0]>=COLUMN || cpy+bias[i][1]+1>=ROW || base[ cpy+bias[i][1]+1 ][  cpx+bias[i][0] ].cls != null )
		{
			bottomFlagY = cpy;
			bottomFlag = true ;
			//reachBottom();//System.out.println("OUT moveDown");
			return ;
		}
	}
	cpy ++;//System.out.println("OUT moveDown");
	
	current.moveDown();

	//if( moveLineIndex != 0)
	//	moveLineIndex = 0;
}

var score = 0;
var reachBottom = function()
{
	bottom && bottom.remove();
	bottomFlag = false ;
	var bias = current.getBias();
	var lineNums =0;
	//var x=0,y=0;
	for( var i =0; i< 4; i++)
	{
		base[ cpy+bias[i][1] ][ cpx+bias[i][0]].cls = current.cls;			
	}

	for( var i=0; i < ROW ; i++)
	{
		var j =0;
		for( ; j <COLUMN; j++)
		{
			if( base[i][j].cls == null)
				break;
		}
		if( j == COLUMN )
		{
			score +=100;
			lineNums ++;
			if( moveLineIndex < i )
				moveLineIndex = i;
			for( var k=i; k >0; k--)
			{
				for( j=0; j <COLUMN; j++)
				{
					base[k][j].cls= base[k-1][j].cls;
					base[k][j].copy(base[k-1][j]);
					base[k][j].remove();
				}
			}
			//System.out.println("REMOVE LINE2");
			for( j=0; j <COLUMN; j++)
				{
					base[0][j].cls= null;
					base[0][j].remove();
				}
			//System.out.println("REMOVE LINE3");
		}
	}

	if( moveLineIndex != 0 )
	{
		smokeNums = SMOKE_NUMS;
	}

	if( lineNums == 2)
	{
		line3Nums = SMOKE_NUMS*5;
		score +=100;         //  bouns
	}
	if( lineNums == 3)
	{
		line3Nums = SMOKE_NUMS*5;
		score +=400;         //  bouns
	}
	if( lineNums == 4)
	{
		line4Nums = SMOKE_NUMS*5;
		score +=1100;	    //  bouns
	}

	if( gameLevel < score / 10000 +1 )
	{
		gameLevel = score / 10000 +1 ;
	}
	
//System.out.println("REMOVE LINE4");

	newGroup();
	
	paint();
	
	// paint score
	$('#score').html('得分：'+score)

}

var toBottom = function()
{
	cpy = bottomY;
	reachBottom();
}

var findBottomPosition = function()
{
	var bias = current.getBias();
	var done = false;
	var y = cpy;

	while( !done )
	{
		for( var i =0; i< 4; i++)//base[x][y];//x:cpx+bias[i][0],Y:cpy+bias[i][1]+1
		{
			if( cpx+bias[i][0]>=COLUMN || y+bias[i][1]+1>=ROW || base[ y+bias[i][1]+1 ][  cpx+bias[i][0] ].cls != null )
			{
				done = true;
				break;
			}
		}
		if( !done)
			y ++;
	}
	bottomY = y; 

}	







$(function(){
$(document).keydown(function(e)    
	    {   	
	        switch(e.which)    
	        {    
	            // user presses the "UP"    
	            case 38:    rotate();    
	                        break;      
	                            
	            // user presses the "DOWN" key    
	            case 40:   moveDown();    
	                        break;    
	            // user presses the "BLANK" key    
	            case 32:   toBottom();    
	            break;    
	                            
	            // user presses the "LEFT" key    
	            case 37:   moveLeft();    
	                        break;    
	                            
	            // user presses the "RIGHT" key    
	            case 39:  moveRight();    
	                        break;    
	        }    
	        paint();
	        return false;
	    });  
});  




